import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_rider/utils/extension.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import '../api/api.dart';
import '../utils/log.dart';

class OssKit {
  OssKit._privateConstructor();
  static final OssKit _instance = OssKit._privateConstructor();
  final _dir = "app/car";
  dynamic _ossParam;

  static OssKit get instance {
    return _instance;
  }

  void getParam({required Function() success, required Function() fail}) {
    if (_ossParam != null) {
      var expire = toInt(_ossParam["expire"]);
      if (expire > DateTime.now().millisecondsSinceEpoch/1000 + 60) {
        success();
        return;
      }
    }
    Api.get(Api.HOST + "/v2/upload/token?dir=$_dir", (data, response) {
      if (data != null) {
        _ossParam = data;
        success();
      } else {
        fail();
      }
    });
  }

  void upload(File file, Function(String) success, Function fail) async {
    getParam(success: () async {
      var filename = const Uuid().v1() + ".jpg";

      Directory tempDir = await getTemporaryDirectory();
      var dd = Directory(tempDir.path + "/image");
      if (dd.existsSync()) {
        dd.deleteSync(recursive: true);
      }
      dd.createSync();

      String tempPath = tempDir.path + "/image/$filename";
      try {
        var compressFile = await FlutterImageCompress.compressAndGetFile(
            file.absolute.path, tempPath,
            minHeight: 800, minWidth: 800);

        var formData = FormData.fromMap({
          "OSSAccessKeyId": _ossParam["access_key_id"],
          "AccessKeySecret": _ossParam["access_key_secret"],
          "policy": _ossParam["policy"],
          "signature": _ossParam["signature"],
          "x-oss-security-token": _ossParam["security_token"],
          "key": _ossParam["dir"] + "/" + filename,
          "file": await MultipartFile.fromFile(compressFile!.path, filename: filename),
        });

        var dio = Dio();
        var resp = await dio.post(_ossParam["upload_oss_url"], data: formData);
        if (resp.data != null) {
          success(_ossParam["upload_oss_url"] + "/" + _ossParam["dir"] + "/" + filename);
        } else {
          fail();
        }
      } catch (error, st) {
        Log.i("上传失败信息", error, st);
        fail();
      }
    }, fail: () {
      fail();
    });
  }
}